package com.jxc.action.spgl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;


import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.jxc.action.BaseAction;
import com.jxc.dao.BaseDaoI;
import com.jxc.model.po.Brand;
import com.jxc.model.po.Discount;
import com.jxc.model.po.Goods;
import com.jxc.model.po.GoodsType;
import com.jxc.model.po.User;
import com.jxc.model.vo.DataGrid;
import com.jxc.model.vo.Json;
import com.jxc.model.vo.SessionInfo;
import com.jxc.model.vo.VBrand;
import com.jxc.model.vo.VGoods;
import com.jxc.model.vo.VRepertory;
import com.jxc.model.vo.VSalelist;
import com.jxc.model.vo.VUser;
import com.jxc.service.BrandServiceI;
import com.jxc.service.GoodsServiceI;
import com.jxc.service.RepertoryServiceI;
import com.jxc.service.UserServiceI;
import com.jxc.util.ExceptionUtil;
import com.jxc.util.ResourceUtil;
import com.opensymphony.xwork2.ModelDriven;


@Namespace("/spgl")
@Action(value = "goodsAction", results = { @Result(name = "goods", location = "/goods/goods.jsp"),
		@Result(name = "goodsAdd", location = "/goods/goodsAdd.jsp"), @Result(name = "goodsEdit", location = "/goods/goodsEdit.jsp"),
		@Result(name = "unsalableGoods", location = "/goods/unsalableGoods.jsp"),@Result(name = "PSIDaily", location = "/goods/PSIDaily.jsp") })
public class GoodsAction extends BaseAction implements ModelDriven<VGoods> {
	private final static Logger logger = Logger.getLogger(GoodsAction.class);

	private VGoods model = new VGoods();

	@Autowired
	private GoodsServiceI goodsService;
	@Autowired
	private UserServiceI userService;
	@Autowired
	private BaseDaoI<User> userdao;
	@Autowired
	private BrandServiceI brandService;
	@Autowired
	private BaseDaoI<Goods> goodsDao;
	@Autowired
	private BaseDaoI<Discount> discountDao;
	@Autowired
	private BaseDaoI<GoodsType> typeDao;
	public String goods() {
		getSubAuths("SPGL_SPGL");
		return "goods";
	}

	public String goodsAdd() {
		return "goodsAdd";
	}

	public String goodsEdit() {
		return "goodsEdit";
	}

	public String unsalableGoods() {
		return "unsalableGoods";
	}

	public void unsaleDatagrid() {
	
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());
			if (vuser.getReid() != null) {
				model.setRid(vuser.getReid());
				this.writeJson(goodsService.unsaleDatagrid(model));
				
			} else {
				VBrand vrepertory = new VBrand();
				vrepertory.setUid(sessionInfo.getUserId());
				List<VBrand> vrepertories = brandService.findlist(vrepertory);
				if (vrepertories != null && vrepertories.size() > 0) {
					List<VGoods> rows = new ArrayList<VGoods>();
					Long total = 0l;
					for (VBrand vre : vrepertories) {
						//model.setRid(vre.getId());
						if(model.getBid()==null){
						model.setBid(vre.getId());
						}
						DataGrid subDg = goodsService.unsaleDatagrid(model);
						rows.addAll(subDg.getRows());
						total += subDg.getTotal();
					}
					DataGrid totalDg = new DataGrid();
					totalDg.setRows(rows);
					totalDg.setTotal(total);
					this.writeJson(totalDg);
				} else {
					DataGrid dg = new DataGrid();
					dg.setTotal(0l);
					dg.setRows(new ArrayList<VGoods>());
					this.writeJson(dg);
				}
			}
		
	}

	public void datagrid() {
		// 查询当前用户所属仓库，将仓库添加到查询条件中
		// 如当前用户没有所属仓库，则查询经销商为当前用户的仓库，将所有仓库中的品牌查询出来
		// 如当前用户没有所属仓库，也没有哪个仓库的经销商为当前用户，则返回为空！
		try {
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());
			if (vuser.getReid() != null) {
				model.setRid(vuser.getReid());
				this.writeJson(goodsService.datagrid(model));
			} else if(vuser.getUserType()!=null&&(vuser.getUserType()==1||vuser.getUserType()==5||vuser.getUserType()==2)){
				model.setUid(vuser.getId());
				
				
				
				this.writeJson(goodsService.datagrid(model));
			}else{
				DataGrid dg = new DataGrid();
				dg.setTotal(0l);
				dg.setRows(new ArrayList<VGoods>());
				this.writeJson(dg);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void goodsMatchDatagrid() {
		DataGrid dg = new DataGrid();
		try {
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get((userService.get(sessionInfo.getUserId())).getUpid());
			dg = goodsService.matchGoods(model.getId(),vuser);
		} catch (Exception e) {
			e.printStackTrace();
			dg.setTotal(0l);
			dg.setRows(new ArrayList<VGoods>());
		}
		this.writeJson(dg);
	}
	
	public void datagridNoLimit() {
		// 查询当前用户所属仓库，将仓库添加到查询条件中
		// 如当前用户没有所属仓库，则查询经销商为当前用户的仓库，将所有仓库中的品牌查询出来
		// 如当前用户没有所属仓库，也没有哪个仓库的经销商为当前用户，则返回为空！
		
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());
			if (vuser.getReid() != null) {
				model.setRid(vuser.getReid());
				this.writeJson(goodsService.datagrid(model));
			} else if(vuser.getUserType()!=null&&(vuser.getUserType()==1||vuser.getUserType()==5)){
				model.setUid(vuser.getId());
				this.writeJson(goodsService.datagrid(model));
			}else{
				DataGrid dg = new DataGrid();
				dg.setTotal(0l);
				dg.setRows(new ArrayList<VGoods>());
				this.writeJson(dg);
			}
	}

	public void noAuth_noPageDatagrid() {
		try {
			if (StringUtils.isBlank(model.getBarcode()) && StringUtils.isBlank(model.getType())) {
				this.writeJson(new ArrayList<VGoods>());
			} else
				this.writeJson(goodsService.findAmountsNoLimit(model));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 用于响应前台销售款号自动完成动作
	 */
	public void noAuth_noPageAutocomplete() {
		try {
			if(this.getRequest().getParameter("rid")!=null){
				model.setRid(Long.parseLong(this.getRequest().getParameter("rid")));
				if(this.getRequest().getParameter("searchType")!=null){
					model.setType(this.getRequest().getParameter("searchType"));
//					model.setType("AD3830");
					this.writeJson(goodsService.findAutocomplete(model));
				}
			}else{
				this.writeJson(new ArrayList<VGoods>());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

//	/**
//	 * 添加品牌
//	 */
//	public void add() {
//		Json j = new Json();
//		try {
//			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
//			VGoods param = new VGoods();
//			param.setBarcode(model.getBarcode());
//			param.setUid(sessionInfo.getUserId());
//			List<VGoods> vgs = goodsService.searchNoLike(param);
//			
//			model.setAmount(0);
//			model.setInitAmount(new Long(0));
//			model.setOrderTotal(new Long(0));
//			model.setOrderReturnTotal(new Long(0));
//			model.setSaleTotal(new Long(0));
//			model.setSaleReturnTotal(new Long(0));
//			model.setDamageTotal(new Long(0));
//			model.setTransferTotal(new Long(0));
//			model.setRepertoryTotal(new Long(0));
//			model.setIsDelete(false);
//			model.setLastedSaleTime(new Date());
//			if (vgs.size() > 0) {
//				throw new Exception();
//			}
//			goodsService.save(model);
//			j.setMsg("添加成功！");
//			j.setSuccess(true);
//		} catch (Exception e) {
//			j.setMsg("添加失败，商品已存在！");
//			logger.info(ExceptionUtil.getExceptionMessage(e));
//		}
//		super.writeJson(j);
//	}
	
	/**
	 * 添加品牌，支持批量添加
	 */
	public void add() {
		Json j = new Json();
		try {
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			
			String color=model.getColor();
			String size=model.getSize();
			
			model.setAmount(0);
			model.setInitAmount(new Long(0));
			model.setOrderTotal(new Long(0));
			model.setOrderReturnTotal(new Long(0));
			model.setSaleTotal(new Long(0));
			model.setSaleReturnTotal(new Long(0));
			model.setDamageTotal(new Long(0));
			model.setTransferTotal(new Long(0));
			model.setRepertoryTotal(new Long(0));
			model.setIsDelete(false);
			model.setLastedSaleTime(new Date());
			
			//保存成功计数器
			int success=0;
			
			//失败计数器
			int fail=0;
			
			//1、先分割color
			//2、分割size
			
			String [] colors=color.split(",");
			String [] sizes=size.split(",");
			
			//外循环颜色
			//内循环尺码
			for (String cols : colors) {
				String colorTmp=cols;
				
				for (String sizs : sizes) {
					String tmpSize=sizs;
					
					VGoods goods=new VGoods();
					//拷贝属性
					BeanUtils.copyProperties(model, goods);
					//设置条码和颜色
					//颜色
					goods.setColor(colorTmp);
					//条码
					goods.setSize(tmpSize);
					//保存对象
					try{
						goodsService.save(goods);
						success++;
					}catch (Exception e) {
						fail++;
					}	
				}	
			}
			/*
			//检测重复 vgs.size()>0 就存在
			VGoods param = new VGoods();
			param.setBarcode(model.getBarcode());
			param.setUid(sessionInfo.getUserId());
			List<VGoods> vgs = goodsService.searchNoLike(param);
			*/
			j.setMsg("添加成功！成功添加 "+success+" 条商品信息！ 失败 "+fail+" 条！");
			j.setSuccess(true);
		} catch (Exception e) {
			j.setMsg("添加失败，请检查输入的值是否合法！");
			logger.info(ExceptionUtil.getExceptionMessage(e));
		}
		super.writeJson(j);
	}

	/**
	 * 修改品牌
	 * 
	 */
	public void edit() {
		Json j = new Json();
		try {
			VGoods param = new VGoods();
			param.setBarcode(model.getBarcode());
			param.setRid(model.getRid());
			List<VGoods> vgs = goodsService.searchNoLike(param);
			if (vgs.size() > 0) {
				for (VGoods vg : vgs) {
					if (vg.getId().longValue() != model.getId().longValue()) {
						throw new Exception();
					}
				}
			}

			goodsService.update(model);
			j.setSuccess(true);
			j.setMsg("编辑成功！");
		} catch (Exception e) {
			logger.error(ExceptionUtil.getExceptionMessage(e));
			j.setMsg("编辑失败，商品已存在！");
		}
		super.writeJson(j);
	}

	/**
	 * 删除品牌
	 * 
	 */
	public void delete() {
		Json j = new Json();
		goodsService.delete(model.getIds());
		j.setSuccess(true);
		j.setMsg("删除成功!");
		super.writeJson(j);
	}

	public void modify() {
		Json j = new Json();
		goodsService.updateLastSaleDate(model.getIds());
		j.setSuccess(true);
		j.setMsg("更新成功!");
		super.writeJson(j);
	}

	public void noAuth_search() {
		Json json = new Json();
		try {
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession()
					.getAttribute(ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());
			List<VGoods> list = new ArrayList<VGoods>();
			if(vuser.getReid()==null){
				model.setUid(vuser.getId());
				list = goodsService.search(model);
			}else{
				model.setRid(vuser.getReid());
				list = goodsService.search(model);
			}
			
			if (list != null && list.size() > 0) {
				writeJson(list);
			}else {
				json.setSuccess(false);
				json.setMsg("没有商品!");
				writeJson(json);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	public void noAuth_searchBarcode() {
		Json json = new Json();
		try {
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			User vuser = userdao.get(User.class,sessionInfo.getUserId());
			if(vuser.getUserType()==3||vuser.getUserType()==4){
				if(vuser.getUser()!=null){
				model.setUid(vuser.getUser().getId());
				}
			}else {
				model.setUid(vuser.getId());
			}
			List<VGoods> list = goodsService.searchNoLike(model);
			System.out.println(list.size());
			if (list != null && list.size()== 0) {
			} else {
				json.setSuccess(false);
				json.setMsg("商品条码重复!请重新输入");
				writeJson(json);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	/*
	 * 退货的商品
	 */
	public void noAuth_search_return(){
		Json json = new Json();
		try {
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession()
					.getAttribute(ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());
			List<VGoods> list = new ArrayList<VGoods>();
			if(vuser.getReid()==null){
				model.setUid(vuser.getId());
				list = goodsService.searchReturn(model);
			}else{
				model.setRid(vuser.getReid());
				list = goodsService.searchReturn(model);
			}
			
			if (list != null && list.size() > 0) {
				writeJson(list);
			}else {
				json.setSuccess(false);
				json.setMsg("没有商品!");
				writeJson(json);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/*
	 * 发货的商品
	 */
	public void noAuth_search_deliver(){
		Json json = new Json();
		try {
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession()
					.getAttribute(ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());
			List<VGoods> list = new ArrayList<VGoods>();
			model.setUid(vuser.getUpid());
			list = goodsService.searchDeliver(model);
			
			if (list != null && list.size() > 0) {
				writeJson(list);
			}else {
				json.setSuccess(false);
				json.setMsg("没有商品!");
				writeJson(json);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@Override
	public VGoods getModel() {
		return model;
	}
	
	public String PSIDaily(){
		return "PSIDaily";
	}
	
	/**
	 * 获取进销存日报表数据后返回统计图给页面
	 * @return
	 * @throws Exception
	 */
	public String PSIDChart() throws Exception {
		SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
		VUser vuser = userService.get(sessionInfo.getUserId());	
		model.setUpid(vuser.getUpid());

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sd1 = new SimpleDateFormat("yyyy-MM-01");
		if (model.getBeginDate() != null) {
			String beginDateStr = sd.format(model.getBeginDate());
			model.setBeginDate(sdf.parse(beginDateStr + " 00:00:00"));
		}else{
			String beginDateStr = sd1.format(new Date());
			model.setBeginDate(sdf.parse(beginDateStr + " 00:00:00"));
		}
		if (model.getEndDate() != null) {
			String endDateStr = sd.format(model.getEndDate());
			model.setEndDate(sdf.parse(endDateStr + " 23:59:59"));
		}else{
			String endDateStr = sd.format(new Date());
			model.setEndDate(sdf.parse(endDateStr + " 23:59:59"));
		}
		
		if (vuser.getReid() != null) {
			model.setRid(vuser.getReid());
		}
		
		if(model.getGroupby()==null||model.getGroupby().trim().equals("")||model.getGroupby().trim().equals("null")){
			model.setGroupby("user");
		}
		
		if(model.getOrder()==null||model.getOrder().trim().equals("")||model.getOrder().trim().equals("null")){
			model.setOrder("total");
		}
		
		
		List<Object[]> vsls = goodsService.PSIDTotal(model);
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("image/jpeg");
		JFreeChart chart = goodsService.getPSIDTotalChart(vsls,model);
		ChartUtilities.writeChartAsJPEG(response.getOutputStream(), chart, 945, 240);
		
		return null;
	}
	
	/**
	 * 获取进销存日报表数据后返回datagrid给页面
	 * @throws Exception
	 */
	public void datagridPSID() throws Exception {
		DataGrid dg = new DataGrid();
		dg.setTotal(0l);
		dg.setRows(new ArrayList<VSalelist>());
		SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
		VUser vuser = userService.get(sessionInfo.getUserId());	
		model.setUpid(vuser.getUpid());

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sd1 = new SimpleDateFormat("yyyy-MM-01");
		if (model.getBeginDate() != null) {
			String beginDateStr = sd.format(model.getBeginDate());
			model.setBeginDate(sdf.parse(beginDateStr + " 00:00:00"));
		}else{
			String beginDateStr = sd1.format(new Date());
			model.setBeginDate(sdf.parse(beginDateStr + " 00:00:00"));
		}
		if (model.getEndDate() != null) {
			String endDateStr = sd.format(model.getEndDate());
			model.setEndDate(sdf.parse(endDateStr + " 23:59:59"));
		}else{
			String endDateStr = sd.format(new Date());
			model.setEndDate(sdf.parse(endDateStr + " 23:59:59"));
		}
		
		if (vuser.getReid() != null) {
			model.setRid(vuser.getReid());
		}
		
		if(model.getGroupby()==null||model.getGroupby().trim().equals("")||model.getGroupby().trim().equals("null")){
			model.setGroupby("user");
		}
		
		if(model.getOrder()==null||model.getOrder().trim().equals("")||model.getOrder().trim().equals("null")){
			model.setOrder("total");
		}
		dg=goodsService.datagridPSID(model);
		this.writeJson(dg);
	}

}
